package com.muyu.file.controller;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.muyu.common.core.domain.Result;
import com.muyu.file.utils.HttpUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * 身份证认证 IdCard
 *
 * @author LeYang
 * on 2024/12/30
 */
@RestController
@RequestMapping("/idCard")
public class IdCardController {

        // @PostMapping 注解来处理 /idCard 路由的 POST 请求
        @PostMapping("/idCard")
        public Result idCard(@RequestParam String name, @RequestParam String idcard) {
            // 调用阿里云身份证验证 API
            try {
                String host = "https://kzidcardv1.market.alicloudapi.com";
                String path = "/api-mall/api/id_card/check";
                String method = "POST";
                String appcode = "303fbf8dcc6b40dd8be310b9441d06ea";  // 替换为你实际的 appcode
                Map<String, String> headers = new HashMap<>();
                headers.put("Authorization", "APPCODE " + appcode);
                headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

                Map<String, String> querys = new HashMap<>();
                Map<String, String> bodys = new HashMap<>();
                bodys.put("name", name);
                bodys.put("idcard", idcard);

                // 发送 HTTP 请求
                HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
                // 获取返回的响应体（JSON格式）
                String responseBody = EntityUtils.toString(response.getEntity());

                // 使用 Fastjson 库解析返回的 JSON
                JSONObject jsonResponse = JSON.parseObject(responseBody);
                JSONObject data = jsonResponse.getJSONObject("data"); // 提取 "data" 部分

                // 将 "data" 部分封装到 Result 中并返回
                return Result.success(data);  // 返回成功的 Result
            } catch (Exception e) {
                e.printStackTrace();
                return Result.error("身份证验证失败：" + e.getMessage());  // 处理异常并返回失败信息
            }
        }



}
